package com.seeyon.apps.ddkk.manager;

import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.logging.log4j.util.Strings;

import com.seeyon.apps.collaboration.manager.ColManager;
import com.seeyon.apps.collaboration.po.ColSummary;
import com.seeyon.apps.ddkk.dao.QiangsDao;
import com.seeyon.apps.kk.constants.Constants;
import com.seeyon.apps.kk.manager.AdapterSyncDataManager;
import com.seeyon.cap4.form.bean.FormBean;
import com.seeyon.cap4.form.bean.FormDataMasterBean;
import com.seeyon.cap4.form.bean.FormFieldBean;
import com.seeyon.ctp.common.config.manager.ConfigManager;
import com.seeyon.ctp.common.exceptions.BusinessException;
import com.seeyon.ctp.common.po.config.ConfigItem;
import com.seeyon.ctp.util.DateUtil;
import com.seeyon.ctp.util.FlipInfo;
import com.seeyon.ctp.util.ParamUtil;

public class SyncFlowLogManagerImpl extends AdapterSyncDataManager {

	private QiangsDao qiangsDao;
	private ColManager colManager;
	private ConfigManager configManager;
	private static final Log log = LogFactory.getLog(AdapterSyncDataManager.class);
	
	public void setConfigManager(ConfigManager configManager) {
		this.configManager = configManager;
	}

	public void setQiangsDao(QiangsDao qiangsDao) {
		this.qiangsDao = qiangsDao;
	}

	public void setColManager(ColManager colManager) {
		this.colManager = colManager;
	}

	@Override
	public boolean isUnflow() {
		// TODO Auto-generated method stub
		return false;
	}

	@Override
	public String getFormCode() {
		// TODO Auto-generated method stub
		return Constants.DDLog;
	}

	@Override
	public String getSendUser() {
		// TODO Auto-generated method stub
		return Constants.createUser;
	}

	@Override
	public void delHistoryData() {
		// TODO Auto-generated method stub
		
	}

	@Override
	public List<Map> getSyncData() {
		// TODO Auto-generated method stub
		List<Map> retList = new ArrayList<Map>();
		int page = 1;
		int size = 200;
		boolean isAdd = true;
		FlipInfo flipInfo = new FlipInfo(page, size);
		FormBean formBean = null;
		try {
			formBean = formApi4Cap4.getFormByFormCode(Constants.nodeFormCode);
		} catch (BusinessException e1) {
			// TODO Auto-generated catch block
		}
		Date date = null;
		ConfigItem config = configManager.getConfigItem("DD Flow Log", "runtime");
		if(config != null){
			String timeStr = config.getConfigValue();
			if(Strings.isNotEmpty(timeStr)){
				try {
					date = DateUtil.parse(timeStr, "yyyy-MM-dd HH:mm:ss");
				} catch (ParseException e) {
					// TODO Auto-generated catch block
				}
			}
			isAdd = false;
		} else {
			config = new ConfigItem();
    		config.setIdIfNew();
    		config.setConfigCategory("DD Flow Log");
    		config.setConfigItem("runtime");
    		config.setCreateDate(DateUtil.currentTimestamp());
    		config.setModifyDate(DateUtil.currentTimestamp());
		}
		
		boolean loop = true;
		while(loop){
			try {
				flipInfo = qiangsDao.findLogList(date , formBean, flipInfo);
			} catch (BusinessException e1) {
				log.error("##客开日志: ", e1);
			}
			List<Map> list = flipInfo.getData();
			if(list.size() != size){
				loop = false;
				date = DateUtil.currentDate();
			} else {
				flipInfo.setPage(page++);
			}

			for(Map params: list){
				try {
					Long summaryId = ParamUtil.getLong(params, "流程id", null);
					if(null != summaryId){
						String nodeName = ParamUtil.getString(params, "流程节点名", null);
						ColSummary summary = colManager.getSummaryById(summaryId);
						if(null != summary){
							Long formId = summary.getFormAppid();
							FormBean ddflowBean = formApi4Cap4.getFormByFormCode(Constants.ddApplyCode);
				            FormBean renewBean = formApi4Cap4.getFormByFormCode(Constants.ddRenew);
				            if(ddflowBean.getId().equals(formId)
				            		|| renewBean.getId().equals(formId)){
				            	FormBean bean = formApi4Cap4.getForm(formId);
				            	Long masterId = summary.getFormRecordid();
				            	FormDataMasterBean masterBeanData = formApi4Cap4.findDataById(masterId, formId, null);
				            	if(null != masterBeanData) {
				            		String flowNo = masterBeanData.getFieldValue(bean.getFieldBeanByDisplay("经销商ID").getName())== null ? ""
					            			: masterBeanData.getFieldValue(bean.getFieldBeanByDisplay("经销商ID").getName()).toString();
					            	params.put("流水号", flowNo);
					            	retList.add(params);
					            	
					            	if("Coupa审批".equals(nodeName)){
					            		Map map1 = new HashMap();
					            		map1.put("流水号", flowNo);
					            		map1.put("表单名", ParamUtil.getString(params, "表单名", null));
					            		map1.put("表单标题", ParamUtil.getString(params, "表单标题", null));
					            		map1.put("流程节点名", "SO Coupa审批日期");
					            		map1.put("动作内容", "同意");
					            		map1.put("流程id", summaryId.toString());
					            		map1.put("操作时间", masterBeanData.getFieldValue(bean.getFieldBeanByDisplay("SO COUPA 审批日期1").getName()));
					            		retList.add(map1);
					            		
					            		Map map2 = new HashMap();
					            		map2.put("流水号", flowNo);
					            		map2.put("表单名", ParamUtil.getString(params, "表单名", null));
					            		map2.put("表单标题", ParamUtil.getString(params, "表单标题", null));
					            		map2.put("流程节点名", "BU Head Coupa审批日期");
					            		map2.put("动作内容", "同意");
					            		map2.put("流程id", summaryId.toString());
					            		map2.put("操作时间", masterBeanData.getFieldValue(bean.getFieldBeanByDisplay("BU Head Coupa审批日期1").getName()));
					            		retList.add(map2);
					            		
					            		Map map3 = new HashMap();
					            		map3.put("流水号", flowNo);
					            		map3.put("表单名", ParamUtil.getString(params, "表单名", null));
					            		map3.put("表单标题", ParamUtil.getString(params, "表单标题", null));
					            		map3.put("流程节点名", "HCCO Coupa审批日期");
					            		map3.put("动作内容", "同意");
					            		map3.put("流程id", summaryId.toString());
					            		map3.put("操作时间", masterBeanData.getFieldValue(bean.getFieldBeanByDisplay("HCCO Coupa审批日期1").getName()));
					            		retList.add(map3);
			
					            		Map map4 = new HashMap();
					            		map4.put("流水号", flowNo);
					            		map4.put("表单名", ParamUtil.getString(params, "表单名", null));
					            		map4.put("表单标题", ParamUtil.getString(params, "表单标题", null));
					            		map4.put("流程节点名", "GM Coupa审批日期");
					            		map4.put("动作内容", "同意");
					            		map4.put("流程id", summaryId.toString());
					            		map4.put("操作时间", masterBeanData.getFieldValue(bean.getFieldBeanByDisplay("GM Coupa审批日期1").getName()));
					            		retList.add(map4);
			
					            		Map map5 = new HashMap();
					            		map5.put("流水号", flowNo);
					            		map5.put("表单名", ParamUtil.getString(params, "表单名", null));
					            		map5.put("表单标题", ParamUtil.getString(params, "表单标题", null));
					            		map5.put("流程节点名", "亚太HCCO Coupa审批日期");
					            		map5.put("动作内容", "同意");
					            		map5.put("流程id", summaryId.toString());
					            		map5.put("操作时间", masterBeanData.getFieldValue(bean.getFieldBeanByDisplay("亚太HCCO Coupa审批日期1").getName()));
					            		retList.add(map5);
					            		
					            		Map map6 = new HashMap();
					            		map6.put("流水号", flowNo);
					            		map6.put("表单名", ParamUtil.getString(params, "表单名", null));
					            		map6.put("表单标题", ParamUtil.getString(params, "表单标题", null));
					            		map6.put("流程节点名", "HCC留用日期");
					            		map6.put("动作内容", "同意");
					            		map6.put("流程id", summaryId.toString());
					            		map6.put("操作时间", masterBeanData.getFieldValue(bean.getFieldBeanByDisplay("HCC留用审批日期").getName()));
					            		retList.add(map6);
			
					            		Map map7 = new HashMap();
					            		map7.put("流水号", flowNo);
					            		map7.put("表单名", ParamUtil.getString(params, "表单名", null));
					            		map7.put("表单标题", ParamUtil.getString(params, "表单标题", null));
					            		map7.put("流程节点名", "启信宝定制报告生成时间");
					            		map7.put("动作内容", "同意");
					            		map7.put("流程id", summaryId.toString());
					            		map7.put("操作时间", masterBeanData.getFieldValue(bean.getFieldBeanByDisplay("生成报告时间").getName()));
					            		retList.add(map7);
					            	} else if("系统校验-确认承诺函已签署".equals(nodeName)){
					            		Map map1 = new HashMap();
					            		map1.put("流水号", flowNo);
					            		map1.put("表单名", ParamUtil.getString(params, "表单名", null));
					            		map1.put("表单标题", ParamUtil.getString(params, "表单标题", null));
					            		map1.put("流程节点名", "承诺函导入时间");
					            		map1.put("动作内容", "同意");
					            		map1.put("流程id", summaryId.toString());
					            		map1.put("操作时间", masterBeanData.getFieldValue(bean.getFieldBeanByDisplay("承诺函签署时间").getName()));
					            		retList.add(map1);
					            	}
				            	}
				            }
						}
					}
				} catch (Exception e) {
					// TODO Auto-generated catch block
					log.error("##客开日志: ", e);
				}
			}
		} 
		
		config.setConfigValue(DateUtil.format(date, "yyyy-MM-dd HH:mm:ss"));
		if(isAdd){
			configManager.addConfigItem(config);
		} else {
			configManager.updateConfigItem(config);
		}
		return retList;
	}

	@Override
	public Map<String, Object> data2FormMap(Map params) {
		// TODO Auto-generated method stub
		return null;
	}

	@Override
	public Object vaildateDataUnique() {
		// TODO Auto-generated method stub
		return "流程id,流程节点名,操作人";
	}
	
	public int saveOrUpdateData(Map<String, Object> params) throws Exception{
		FormBean bean = formApi4Cap4.getFormByFormCode(getFormCode());
		FormDataMasterBean formDataMasterBean = null;
		boolean isMainAdd = false;
		Object unique = vaildateDataUnique();
		if(unique == null){
			isMainAdd = true;
		} else if(unique instanceof String
				|| unique instanceof Map){
			Map<String, Object> vmap = new HashMap<String, Object>();
			String fields = null;
			if(unique instanceof Map){
				fields = ((Map) unique).get("main").toString();
			} else {
				fields = unique.toString();
			}
			for(String fieldDisplay: fields.split(",")){
				FormFieldBean field = bean.getFieldBeanByDisplay(fieldDisplay);
				if(field != null && field.isMasterField()){
					formDataBaseManager.change2Map(field, params.get(fieldDisplay), vmap);
				}
			}
			if(vmap.isEmpty()){
				isMainAdd = true;
			} else {
				FlipInfo flipInfo = new FlipInfo(1, 200);
				List<FormDataMasterBean> masterDataList = formApi4Cap4.findMasterDataList(flipInfo, bean.getId(), null, vmap);
				if(CollectionUtils.isNotEmpty(masterDataList)){
					isMainAdd = true;
					for(FormDataMasterBean dataMaster: masterDataList){
						boolean isUnique = false;
						for(String fieldName: vmap.keySet()){
							if(vmap.get(fieldName) == null){
								if(dataMaster.getFieldValue(fieldName) == null
										&& bean.getFieldBeanByName(fieldName).getDisplay().equals("操作人")){
									isUnique = true;
								} else {
									isUnique = false;
									break;
								}
							} else if(vmap.get(fieldName).equals(dataMaster.getFieldValue(fieldName))){
								if(bean.getFieldBeanByName(fieldName).getDisplay().equals("操作人")){
									isUnique = false;
									break;
								} else {
									isUnique = true;
								}
							} else {
								isUnique = false;
								break;
							}
							
						}
						if(isUnique){
							isMainAdd = false;
							formDataMasterBean = formApi4Cap4.findDataById(dataMaster.getId(), bean, null);
							break;
						}
					}
				} else {
					isMainAdd = true;
				}
			}
		} else {
			isMainAdd = true;
		}
		
		if(isMainAdd){
			try{
				formDataBaseManager.saveUnflowData(getFormCode(), getSendUser(), params);
				return 1;//新增成功
			} catch(Exception e){
				log.error("##客开日志: ", e);
				return 0;//新增失败
			}
		} else {
			String ret = "";
			try{
				if(unique instanceof Map){
					((Map)unique).remove("main");
					ret = formDataBaseManager.updateFormData(getFormCode(), formDataMasterBean, params, (Map)unique);
				} else {
					ret = formDataBaseManager.updateFormData(getFormCode(), formDataMasterBean, params, null);
				}
			} catch(Exception e){
				log.error("##客开日志: ", e);
				return 2;//更新失败
			}
			if(Strings.isEmpty(ret)){
				return 3;//未更新
			} else {
				return 4;//更新成功
			}
		}
	}

}
